/*
 * Copyright (c) 2015. For Intelligent Group.
 */

package com.intelligent.ispc.common.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by Peter on 2016-03-18.
 */
public class ApplicationUtil {

    public static String getProjectPathWithSeparator() {
        String result = ApplicationUtil.class.getResource("ApplicationUtil.class").getPath().toString();
        int index = result.indexOf("WEB-INF");
        if (index == -1) {
            index = result.indexOf("bin");
        }

        result = result.substring(0, index);
        if (result.startsWith("file")) {
            if(getOsName().contains("Windows")) {
                result = result.substring(6);
            } else {
                result = result.substring(5);
            }

        } else if (result.startsWith("jar")) {
            result = result.substring(10);
        }

//        if (result.startsWith("/"))
//            result = result.substring(1);
        return result;
    }

    public static String getProjectPath() {
        String result = getProjectPathWithSeparator();
        if (result.endsWith(getFileSeparator()))
            result = result.substring(0, result.length() - 1);
        return result;
    }

    public static String getApplicationName() {
        String result = getProjectPath();
        result = result.substring(result.lastIndexOf(getFileSeparator()) + 1);
        return result;
    }

    public static String getBasePathNotContainServerName(HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        sb.append(request.getScheme());
        sb.append("://");
        sb.append(request.getServerName());
        sb.append(":");
        sb.append(request.getServerPort());
        return sb.toString();
    }

    public static String getFileSeparator() {
        return System.getProperties().getProperty("file.separator");
    }

    public static String getOsName() {
        return System.getProperties().getProperty("os.name");
    }
}
